var XHR = function(method, ad, params) {
    var xhr = new XMLHttpRequest();
    xhr.onload = params.onload || null;
    xhr.open(method, ad);
    if (method === 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    var variables = params.variables || null
            , str = '';
    for (var i in variables) {
        str += i + '=' + encodeURIComponent(variables[i]) + '&';
    }
    xhr.send(str);
};

var mode = 'normal';

function init() {

    // Connect to the SocketIO server to retrieve ongoing games.
    socket = io.connect();
    socket.on('participants', function(data) {
        computeParticipants(data);
    });
    socket.on('FinalCountDown', function(data) {
        countdown(data.FinalCountDown / 1000);
    });
    socket.on('TerminateGame', function(data) {
        terminateGame(data);
    });
    socket.on('solutions', function(data) {
        computeSolutions(data);
    });
    socket.emit('identification', {login: document.getElementById('login').value
        , idGame: document.getElementById('idGame').value}
    );
}

function computeParticipants(data) {
    var dl = document.getElementById('players');
    dl.innerHTML = '';
    for (p in data.participants) {
        playerName = document.createElement('dt');
        playerName.innerText = data.participants[p];
        dl.appendChild(playerName);

        playerMoves = document.createElement('dd');
        playerMoves.innerText = 'Pas de solution';
        dl.appendChild(playerMoves);
    }
}

function terminateGame(data) {
    game = document.getElementById('game');

    li = document.createElement('li');
    li.innerText = getPlayerA(solution['player']) + ' gagné la partie !';
    game.appendChild(li);

    li = document.createElement('li');
    li.innerText = 'La partie est terminée';
    game.appendChild(li);
}

function computeSolutions(data) {
    console.log('Solutions are :\n' + JSON.stringify(data.solutions));
    solution = data.solutions[data.solutions.length - 1];

    moves = solution['proposition'].length / 2;
    li = document.createElement('li');
    li.innerText = getPlayerA(solution['player']) + ' trouvé une solution (' + moves + ' mouvements)';
    document.getElementById('game').appendChild(li);

    displayPlayerMoves(solution['player'], moves);
}

function displayPlayerMoves(player, moves) {
    players = document.querySelectorAll('#players > *');
    for (i = 0; i < players.length; i++) {
        if (players[i].innerText === player) {
            players[i+1].innerText = moves + ' mouvements';
            break;
        }
    }
}

function getPlayerA(player) {
    if(player === $('#login').val()) {
        return 'Tu as';
    }
    return player+' a';
}